package com.skytech.component.crawler.scratch;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class QuartzConfigService {

    @Autowired
    private QuartzConfigDAO quartzConfigDAO;

    @Autowired
    private TaskStatusDAO taskStatusDAO;




    public void addTaskQuartz(QuartzConfig quartzConfig)  {
        TaskStatus taskStatus=new TaskStatus();
        if(quartzConfigDAO.findByRuleId(quartzConfig.getRuleId()).isEmpty()){
            quartzConfig.setId(UUID.randomUUID().toString());
            quartzConfigDAO.save(quartzConfig);
            if(taskStatusDAO.findAllByRuleId(quartzConfig.getRuleId()).isEmpty()){
                taskStatus.setId(UUID.randomUUID().toString());
                taskStatus.setRuleId(quartzConfig.getRuleId());
                taskStatus.setStatus(State.INIT.toString());
                taskStatusDAO.save(taskStatus);
            }else {
                TaskStatus taskStatusOld=taskStatusDAO.findAllByRuleId(quartzConfig.getRuleId()).get(0);
                taskStatusOld.setStatus(State.INIT.toString());
                taskStatusDAO.save(taskStatusOld);
            }


        }else{
            QuartzConfig quartzConfigOld=quartzConfigDAO.findByRuleId(quartzConfig.getRuleId()).get(0);
            quartzConfigOld.setCron(quartzConfig.getCron());
            quartzConfigDAO.save(quartzConfigOld);

        }

    }


    public void cancelTaskQuartz(QuartzConfig quartzConfig) {
        QuartzConfig quartzConfig1=quartzConfigDAO.findByRuleId(quartzConfig.getRuleId()).get(0);
        quartzConfigDAO.delete(quartzConfig1);

        if(!taskStatusDAO.findAllByRuleId(quartzConfig.getRuleId()).isEmpty()){
            taskStatusDAO.delete(taskStatusDAO.findAllByRuleId(quartzConfig.getRuleId()).get(0));
        }
    }
}
